#!/bin/bash

stop_service()
{
  echo
  echo_info "Clean hyren service ... ..."

  ssh -o StrictHostKeyChecking=no $HRS_REDIS_HOST "$HRS_REDIS_HOME/bin/redis-cli -p $HRS_REDIS_PORT -h $HRS_REDIS_HOST shutdown && sleep 1"

  kill_proc "HYRENSERVWEB"

  su - $HYREN_USER -c "$HRS_PGSQL_HOME/bin/pg_ctl -D $HRS_PGSQL_PGDATA -m immediate stop"
  waiting_proc_status $HRS_PGSQL_PORT 1 "db stop"

  echo_success "clean hyren service done."
}

del_hyrenuser()
{
  echo
  echo_info "Clean hyren user ... ..."
  local value_arr=($HYREN_ALLHOSTS)
  for i in ${value_arr[@]}; do
    echo
    echo_info "clean hyren user on [${i}] =========================="
    ssh -o StrictHostKeyChecking=no $i "userdel -r ${HYREN_USER}" || { echo_warn "del user [$HYREN_USER] fail on ${i}."; }
    ssh -o StrictHostKeyChecking=no $i "egrep \"^${HYREN_USER}:\" /etc/group > /dev/null" && { echo_warn "group [${HYREN_USER}] still exist"; }
    ssh -o StrictHostKeyChecking=no $i "egrep \"^${HYREN_USER}:\" /etc/passwd > /dev/null" && { echo_warn "user [${HYREN_USER}] still exist"; }
    ssh -o StrictHostKeyChecking=no $i "ls /home/${HYREN_USER} > /dev/null 2>&1" && { echo_warn "user home dir [/home/${HYREN_USER}] still exist"; }

    echo_info "clean hyren user on [${i}] ===================== DONE"
  done
  echo
  echo_success "clean hyren user done."
}

del_hyrendir()
{
  echo
  echo_info "Clean hyren dir ... ..."
  local value_arr=($HYREN_ALLHOSTS)
  for i in ${value_arr[@]}; do
    echo
    echo_info "clean hyren user on [${i}] =========================="
    ssh -o StrictHostKeyChecking=no $i "if [ -d \"$HYRENDATA_HOME\" ]; then rm -rf $HYRENDATA_HOME/*; fi" || { echo_warn "del dir [$HYRENDATA_HOME] fail on ${i}."; }
    ssh -o StrictHostKeyChecking=no $i "if [ -d \"$HYRENSOFT_HOME\" ]; then rm -rf $HYRENSOFT_HOME; fi" || { echo_warn "del dir [$HYRENSOFT_HOME] fail on ${i}."; }

    echo_info "clean hyren user on [${i}] ===================== DONE"
  done
  echo
  echo_success "clean hyren dir done."
}

cleanup()
{
  stop_service
  del_hyrenuser
  del_hyrendir
}
